Easy2Siksha.com
GNDU Question Paper-2024
Bachelor of Computer Application
(BCA) 1
st
Semester (CBGS)
INTRODUCTION TO PROGRAMMINGC
Time Allowed: Three Hours Max. Marks: 75
Note: Attempt Five questions in all, selecting at least One question from each section. The
Fifth question may be attempted from any section. All questions carry equal marks.
SECTIONA
1.(a) What is meaning and use of Symbolic Constant ? Give example.
(b) Write a program to get three sides of a Triangle and calculate its area.
2. Explain various formatted and unformatted I/O statements available in C.
SECTIONB
3. Write a program to get a number from user and check whether it is Prime or not.
4. Explain meaning and use of various storage classes available in C. Give example of each.
SECTIONC
5. Write a program using function to get a number from user and find sum of its digits.
6.(a) What is Recursion ? Explain with the help of an example.
(b) What is a string in C ? Explain any five string handling functions available in C.
Easy2Siksha.com
SECTIOND
7. What is User defined data type ? What is use of structure and union in C ? What is
difference between both ?
8. What is a pointer ? Which are different types of pointers in C ? Give examples.
GNDU Answer Paper-2024
Bachelor of Computer Application
(BCA) 1
st
Semester (CBGS)
INTRODUCTION TO PROGRAMMINGC
Time Allowed: Three Hours Max. Marks: 75
Note: Attempt Five questions in all, selecting at least One question from each section. The
Fifth question may be attempted from any section. All questions carry equal marks.
SECTIONA
1.(a) What is meaning and use of Symbolic Constant ? Give example.
(b) Write a program to get three sides of a Triangle and calculate its area.
Ans: Starting with a Little Story
Imagine you’re building a house. You tell the workers,
“Whenever I say Golden Ratio, I mean exactly 1.618.”
Now, instead of repeating “1.618” every time, you just say Golden Ratio and everyone
knows what you mean. If you ever decide to change it to 1.62, you only change it once in
your “rulebook” and the whole team follows it everywhere.
Easy2Siksha.com
That’s exactly what symbolic constants do in programming they give a name to a fixed
value so you can use that name throughout your program instead of writing the number
again and again.
(a) Meaning of Symbolic Constant
A symbolic constant is a name (identifier) that represents a fixed value in a program.
Once defined, its value cannot be changed during program execution.
It’s “symbolic” because it uses a name instead of the raw number.
It’s a “constant” because the value stays the same.
Why Use Symbolic Constants?
1. Readability: Code becomes easier to understand. Instead of:
area = 3.14159 * r * r;
You can write:
area = PI * r * r;
Anyone reading it instantly knows PI is the circle constant.
2. Easy Maintenance: If the value changes, you update it in one place and it updates
everywhere in the program.
3. Avoid Magic Numbers: “Magic numbers” are unexplained numbers in code.
Symbolic constants replace them with meaningful names.
4. Error Prevention: The compiler can warn you if you try to change a constant.
How to Define Symbolic Constants
Method 1: Using #define (Preprocessor Directive)
#define PI 3.14159
#define MAX_STUDENTS 100
No data type is specified.
The preprocessor replaces every occurrence of PI with 3.14159 before compilation.
Method 2: Using const Keyword
const double PI = 3.14159;
const int MAX_STUDENTS = 100;
Has a data type.
The compiler enforces type checking.
Example of Symbolic Constant
Easy2Siksha.com
#include <stdio.h>
#define PI 3.14159
int main() {
double radius = 5.0;
double area = PI * radius * radius;
printf("Area of Circle: %.2f\n", area);
return 0;
}
Here, PI is a symbolic constant. If you change #define PI 3.14159 to #define PI 3.14,
the change reflects everywhere.
(b) Program to Get Three Sides of a Triangle and Calculate its Area
Now, let’s move to the second part — calculating the area of a triangle when you know all
three sides.
The Formula Heron’s Formula
If the sides are a, b, and c:
1. First, find the semi-perimeter:
2. Then, area is:
Why This Formula Works
Heron’s formula is perfect when you don’t know the height of the triangle it uses only the
lengths of the sides.
Program in C
We’ll use a symbolic constant for nothing here except maybe PI if needed, but here the
main focus is the formula.
#include <stdio.h>
#include <math.h> // for sqrt()
int main() {
double a, b, c, s, area;
// Input three sides
printf("Enter the three sides of the triangle: ");
Easy2Siksha.com
scanf("%lf %lf %lf", &a, &b, &c);
// Calculate semi-perimeter
s = (a + b + c) / 2;
// Calculate area using Heron's formula
area = sqrt(s * (s - a) * (s - b) * (s - c));
// Display result
printf("Area of the triangle = %.2lf\n", area);
return 0;
}
Sample Output
Enter the three sides of the triangle: 3 4 5
Area of the triangle = 6.00
Diagram for Better Understanding
Here’s a simple labelled diagram of a triangle for context:
/\
/ \
a / \ b
/ \
/________\
c
Where:
a, b, and c are the three sides.
We don’t need the height for Heron’s formula.
Step-by-Step Flow of the Program
1. Input: Ask the user to enter the three sides.
2. Semi-perimeter Calculation: Add the three sides and divide by 2.
3. Area Calculation: Apply Heron’s formula using sqrt() from <math.h>.
4. Output: Display the area rounded to two decimal places.
2. Explain various formatted and unformatted I/O statements available in C.
Ans: A Different Beginning The Bank Counter Analogy
Imagine you walk into a bank. At one counter, the cashier asks you to fill out a neat form
your name in one box, your account number in another, the amount in a third. Everything is
structured and follows a format. That’s like formatted I/O in C you decide exactly how
the data will be read or displayed.
Easy2Siksha.com
At another counter, the cashier just says, “Tell me your name and amount,” and scribbles it
down as you speak no fixed boxes, no strict structure. That’s like unformatted I/O the
data is taken or given as it is, without extra formatting rules.
In C programming, I/O (Input/Output) statements are the way we talk to the outside world
reading from the keyboard, writing to the screen, or even working with files. And just like
in our bank story, they come in two main flavours:
1. Formatted I/O where you control the format.
2. Unformatted I/O where data is handled in raw form.
Let’s explore both in detail.
1. Formatted I/O Statements in C
Meaning: Formatted I/O functions allow you to specify the format in which data is read or
written. You can decide:
How many decimal places to show.
Whether to print numbers with leading zeros.
How to align text.
Which data types to expect.
These functions use format specifiers like %d, %f, %c, %s to control the input/output.
Common Formatted Output Functions
(a) printf()
Used to display output on the screen.
Syntax:
printf("format string", variable1, variable2, ...);
Example:
int age = 20;
float marks = 88.5;
printf("Age: %d, Marks: %.1f\n", age, marks);
Output:
Code
Age: 20, Marks: 88.5
Here, %d is for integer, %.1f means float with 1 decimal place.
(b) fprintf()
Easy2Siksha.com
Similar to printf() but writes output to a file instead of the screen.
Example:
FILE *fp = fopen("data.txt", "w");
fprintf(fp, "Name: %s, Age: %d\n", "Ravi", 25);
fclose(fp);
(c) sprintf()
Writes formatted output to a string (character array) instead of the screen.
Example:
char str[50];
sprintf(str, "Value: %d", 100);
printf("%s", str);
Common Formatted Input Functions
(a) scanf()
Reads input from the keyboard in a specified format.
Syntax:
scanf("format string", &var1, &var2, ...);
Example:
int age;
scanf("%d", &age);
(b) fscanf()
Reads formatted input from a file.
Example:
FILE *fp = fopen("data.txt", "r");
char name[20];
int age;
fscanf(fp, "%s %d", name, &age);
fclose(fp);
(c) sscanf()
Reads formatted data from a string.
Example:
char data[] = "Ravi 25";
char name[20];
int age;
sscanf(data, "%s %d", name, &age);
Advantages of Formatted I/O
Easy2Siksha.com
Full control over how data appears.
Can handle multiple data types in one statement.
Useful for creating neat tables, reports, and structured files.
2. Unformatted I/O Statements in C
Meaning: Unformatted I/O functions deal with data in a raw, direct way no format
specifiers, no special alignment. They are often used for:
Reading/writing single characters.
Handling strings without formatting.
Fast data transfer.
Common Unformatted Output Functions
(a) putchar()
Writes a single character to the screen.
Example:
putchar('A');
(b) puts()
Writes a string to the screen, followed by a newline.
Example:
puts("Hello World");
(c) fputc()
Writes a single character to a file.
Example
FILE *fp = fopen("data.txt", "w");
fputc('A', fp);
fclose(fp);
(d) fputs()
Writes a string to a file.
Example:
FILE *fp = fopen("data.txt", "w");
fputs("Hello File", fp);
fclose(fp);
Common Unformatted Input Functions
Easy2Siksha.com
(a) getchar()
Reads a single character from the keyboard.
Example:
char ch = getchar();
(b) gets() (unsafe, but historically used)
Reads a string from the keyboard until a newline is encountered.
Example:
char name[20];
gets(name);
(Note: gets() is unsafe and removed from modern C standards; use fgets() instead.)
(c) fgetc()
Reads a single character from a file.
Example:
FILE *fp = fopen("data.txt", "r");
char ch = fgetc(fp);
fclose(fp);
(d) fgets()
Reads a string from a file or keyboard.
Example:
char str[50];
fgets(str, 50, stdin); // from keyboard
Advantages of Unformatted I/O
Simple and fast for basic character or string operations.
Good for low-level file handling.
Less overhead compared to formatted I/O.
3. Quick Comparison Table
Feature
Formatted I/O
Unformatted I/O
Control over
format
Yes
No
Functions
printf, scanf, fprintf, fscanf,
sprintf, sscanf
getchar, putchar, gets, puts, fgetc,
fputc, fgets, fputs
Speed
Slower (due to formatting)
Faster
Easy2Siksha.com
Use case
Structured data, reports,
mixed data types
Simple char/string handling, raw data
4. A Visual Memory Aid
Think of Formatted I/O as a tailor measures, cuts, and stitches exactly to your size and
style. Think of Unformatted I/O as a ready-made shop you take it as it is, no custom
fitting.
5. Example Program Using Both
#include <stdio.h>
int main() {
char name[20];
int age;
// Formatted Input
printf("Enter your name and age: ");
scanf("%s %d", name, &age);
// Formatted Output
printf("Name: %s, Age: %d\n", name, age);
// Unformatted Output
puts("This is unformatted output using puts().");
// Unformatted Input
printf("Enter a single character: ");
char ch = getchar(); // will read leftover newline
ch = getchar(); // actual char
putchar(ch);
return 0;
}
6. Conclusion
In C:
Formatted I/O is your go-to when you need precision and structure perfect for
reports, tables, and mixed data types.
Unformatted I/O is your friend when you need speed and simplicity great for
quick character or string handling.
Easy2Siksha.com
SECTIONB
3. Write a program to get a number from user and check whether it is Prime or not.
Ans: 󷈷󷈸󷈹󷈺󷈻󷈼 A Story-like Explanation
Imagine for a moment that numbers are like people standing in a big line. Each number has
its own unique personality. Some numbers love to share, while others are very private.
Now, there is a special type of number in mathematics called a Prime Number. You can
think of a prime number as a “loner” – it doesn’t like to be divided or shared by many
others. In fact, a prime number only allows two people to divide it:
1. Number 1
2. Itself
That’s it! Nobody else is allowed.
For example:
Take 7. If you try to divide 7 by 2, 3, 4, 5, or 6 it doesn’t work out evenly. Only 1
and 7 divide it perfectly. So, 7 is a prime number.
On the other hand, take 8. Yes, 1 and 8 divide it, but also 2 and 4 divide it. That
means 8 is not prime. It’s a composite number (a number that has more than two
factors).
So the question is asking us:
󷷑󷷒󷷓󷷔 Can you write a program that takes a number from the user and checks whether it is
prime or not?
At first glance, this might look like a coding problem. But at its heart, it’s simply about
understanding the nature of numbers and then teaching the computer how to “think” like
us.
󷊆󷊇 Step 1: Understanding the Problem in Human Terms
When a person asks, “Is this number prime?” what do we normally do?
1. We check if the number is greater than 1, because numbers less than 2 (like 0 and 1)
are not prime.
2. We try to divide the number by smaller numbers.
o If we find a number that divides it evenly, we immediately know it’s not
prime.
o If no such number exists, it is prime.
Easy2Siksha.com
For example:
Let’s say the user enters 11.
o We check: can 11 be divided by 2? No.
o Can it be divided by 3? No.
o By 4, 5, 6, 7, 8, 9, 10? None of them work.
o Only 1 and 11 divide it → so it’s prime.
This is exactly what our program needs to do: copy the same thought process we humans
use.
󷊆󷊇 Step 2: Planning the Program
Before writing code, let’s plan it like a recipe.
1. Take input: Ask the user to enter a number.
2. Check validity: If the number is less than or equal to 1 → it’s not prime.
3. Check divisibility:
o Use a loop to try dividing the number by every integer from 2 up to one less
than the number itself.
o If we find any number that divides it, mark it as not prime.
4. Give the result: Print whether the number is prime or not.
󷊆󷊇 Step 3: Writing the Program in C
Here’s the code written in C language:
#include <stdio.h>
int main() {
int num, i, flag = 0;
// Step 1: Take input from user
printf("Enter a number: ");
scanf("%d", &num);
// Step 2: Check validity
if (num <= 1) {
printf("%d is not a prime number.\n", num);
return 0;
}
// Step 3: Check divisibility
for (i = 2; i < num; i++) {
if (num % i == 0) {
flag = 1; // Found a divisor
break;
}
Easy2Siksha.com
}
// Step 4: Give result
if (flag == 0)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
return 0;
}
󷊆󷊇 Step 4: Explaining the Program
Now let’s explain every piece of the program in plain English so that it feels like we are
reading a story.
#include <stdio.h>
This is like calling a librarian to provide us with useful tools. In this case, it gives us
the printf and scanf functions to interact with the user.
int main()
Every C program starts from here. It’s like the main gate through which the
computer enters the program.
Variable Declaration
int num, i, flag = 0;
o num will store the number entered by the user.
o i will help us in looping.
o flag is like a signal. If we find the number is divisible by someone, we turn the
flag ON (1). If not, we keep it OFF (0).
Taking Input
printf("Enter a number: ");
scanf("%d", &num);
The program politely asks the user to enter a number.
Checking Small Cases
if (num <= 1) {
printf("%d is not a prime number.\n", num);
return 0;
}
Numbers like 0 and 1 are not prime. So we handle them immediately.
The Loop
for (i = 2; i < num; i++) {
if (num % i == 0) {
Easy2Siksha.com
flag = 1; // Found a divisor
break;
}
}
Here’s where the real detective work happens. We try dividing the number by every
possible candidate (from 2 up to num-1).
o If we find someone who divides it perfectly, we raise the flag and stop
checking further.
Final Result
if (flag == 0)
printf("%d is a prime number.\n", num);
else
printf("%d is not a prime number.\n", num);
At the end, if the flag is still 0, it means nobody (except 1 and itself) could divide the
number → Prime! Otherwise, it’s not prime.
󷊆󷊇 Step 5: Thinking Beyond
What if the number is really big, like 1,000,000? Checking every number up to 999,999
would be too slow. A smarter way is to check only up to the square root of the number. But
since this is a beginner-friendly explanation, we stick with the simple method. Still, it’s nice
to know that optimization exists!
󷈷󷈸󷈹󷈺󷈻󷈼 Wrapping Up
So, the question “Write a program to check whether a number is prime or not” is not just
about code. It’s about teaching the computer how humans naturally think about prime
numbers.
We began by imagining numbers as people with unique personalities. Then we understood
the concept of prime numbers in real-life terms. After that, we designed a plan, wrote the C
program, and explained it step by step.
The beauty of this exercise is that it doesn’t just solve a problemit also builds our logical
thinking. Next time someone asks you, “Is 29 prime?”, you’ll know not just the answer but
also the process of finding itand even how to make a computer do the hard work for you!
Easy2Siksha.com
4. Explain meaning and use of various storage classes available in C. Give example of each.
Ans :A Friendly Start
Imagine you are the manager of a big office. In your office, there are many employees, but
not everyone works in the same way. Some employees come daily and leave by evening.
Some are permanent employees who are remembered by the office system even if they are
absent. A few are interns who work temporarily. Others are hidden workers who do their
work quietly in a corner but no one outside the office knows about them.
In the same way, in the C programming language, variables (the employees) are managed by
storage classes (the office rules). Storage classes decide where the variable will live
(memory location), how long it will stay alive (lifetime), who can use it (scope), and what
its initial value will be (default initialization).
C provides four major storage classes:
1. Automatic (auto)
2. Register
3. Static
4. External (extern)
Let’s take a friendly tour of each one, like introducing different types of employees in our
imaginary office.
1. Automatic Storage Class (auto)
Think about the employees who come to the office in the morning and leave in the evening.
They don’t stay once the office is closed. Their presence is only temporary.
In C, such employees are like automatic variables.
Scope: Local (they can only be used inside the block/function where they are
declared).
Lifetime: They exist only while the function is running. When the function ends, they
are destroyed.
Default value: Garbage (random value, unless we explicitly assign one).
Keyword: auto (though by default, every local variable is auto, so the keyword is
rarely written).
󷷑󷷒󷷓󷷔 Example of auto:
#include <stdio.h>
void demoAuto() {
auto int x = 10; // automatic variable
printf("Value of auto variable x = %d\n", x);
Easy2Siksha.com
}
int main() {
demoAuto();
// printf("%d", x); // Error: x is not accessible here
return 0;
}
Here, variable x is like a daily employee. It is created when the function demoAuto() starts,
and it disappears after the function ends.
2. Register Storage Class (register)
Now think about employees who are very fast and efficient. They don’t sit at faraway desks
but are given a special seat right near the manager so they can work quickly.
In C, such employees are like register variables. They are stored not in normal memory
(RAM) but inside the CPU registers for quick access.
Scope: Local (only inside the function/block).
Lifetime: Exists till the function is running.
Default value: Garbage.
Keyword: register.
Special point: You cannot take the address of a register variable using &, because
they are not in normal memory.
󷷑󷷒󷷓󷷔 Example of register:
#include <stdio.h>
void demoRegister() {
register int counter = 1;
for(counter; counter <= 5; counter++) {
printf("Counter: %d\n", counter);
}
}
int main() {
demoRegister();
return 0;
}
Here, the loop variable counter is kept in the CPU register, making the loop execution faster
(in concept).
3. Static Storage Class (static)
Easy2Siksha.com
Now imagine an employee who is permanently attached to the company. Even if he doesn’t
appear every day in the office, his data and contribution are remembered. Next time he
comes, the office system recalls all his past records.
In C, these are static variables.
Scope: Local (if declared inside a function) or global (if declared outside).
Lifetime: Whole program execution (they exist permanently).
Default value: 0 (if not initialized).
Keyword: static.
󷷑󷷒󷷓󷷔 Example of static:
#include <stdio.h>
void demoStatic() {
static int count = 0; // initialized only once
count++;
printf("Count = %d\n", count);
}
int main() {
demoStatic();
demoStatic();
demoStatic();
return 0;
}
Output:
Count = 1
Count = 2
Count = 3
Here, count remembers its previous value across function calls. Unlike auto, it is not
destroyed after the function ends.
4. External Storage Class (extern)
Finally, imagine employees who don’t work in one office but are known to the whole
organization. Any branch or department can access their details.
In C, these are external variables.
Scope: Global (accessible across multiple functions and even files).
Lifetime: Entire execution of the program.
Default value: 0.
Keyword: extern.
Easy2Siksha.com
󷷑󷷒󷷓󷷔 Example of extern:
#include <stdio.h>
int globalVar = 50; // global variable
void showExtern() {
extern int globalVar; // declare external variable
printf("Value of globalVar = %d\n", globalVar);
}
int main() {
showExtern();
globalVar = 100; // modify global variable
showExtern();
return 0;
}
Here, globalVar is like an employee who is recognized everywhere in the organization. Any
function can access or modify it.
A Quick Comparison Table
Storage
Class
Keyword
Scope
Lifetime
Example Use
Case
Automatic
auto
Local
Function
runtime only
Normal local
variables
Register
register
Local
Function
runtime only
Fast counters,
loop variables
Static
static
Local/Global
Whole program
execution
Retaining values
between calls
External
extern
Global
Whole program
execution
Sharing variables
across files
Wrapping It Up Like a Story
So, let’s recall our office analogy:
Auto = temporary employees (local, disappear after work).
Register = super-fast employees with a desk near the boss (stored in CPU registers).
Static = permanent employees whose history is remembered (value retained).
Extern = employees known across the entire organization (global variables).
Easy2Siksha.com
Storage classes are not just about theory; they are powerful tools that allow a programmer
to manage memory, speed, and accessibility wisely. Just like a good manager assigns tasks
smartly to employees, a good programmer assigns storage classes carefully to variables.
SECTIONC
5. Write a program using function to get a number from user and find sum of its digits.
Ans: 󷈷󷈸󷈹󷈺󷈻󷈼 The Story-like Explanation
Imagine one fine day, you are sitting at your desk with a notebook and pen. Suddenly, your
math teacher walks in and says:
“Take any number you like. Now, break it apart digit by digit and find the total of all those
digits.”
You smile, thinkingThat’s easy! For example, if I take the number 2468, the digits are 2, 4,
6, and 8. Adding them gives 20.
This simple little game of breaking a number and adding its digits is exactly what computers
can do as well. The only difference is, the computer doesn’t have fingers to count. Instead, it
uses logic, loops, and functions.
Now, our task is to write a program in C language that asks the user for a number, breaks it
down into digits, adds those digits, and finally shows the result.
Sounds simple, right? But here’s the interesting part: we will not just write the program
we’ll understand why and how every line works.
󷘹󷘴󷘵󷘶󷘷󷘸 Breaking Down the Question
The question is asking for three things:
1. Write a program in C language.
So our final solution must be in the C programming language.
2. Use functions.
That means instead of writing everything inside the main() function, we will create a
separate function to calculate the sum of digits. Functions make our program neat,
reusable, and easy to understand.
3. Find the sum of digits of a number given by the user.
Which means:
o The user will enter a number.
o We will take that number, split its digits, and keep adding them one by one.
Easy2Siksha.com
o Finally, we will display the sum.
󼩺󼩻 Step 1: Understanding How to Split Digits
Suppose the user gives the number 1234. How can we get its digits one by one?
Here’s the trick:
If we divide 1234 by 10, we get quotient = 123 and remainder = 4. The remainder is
the last digit.
If we again divide 123 by 10, we get quotient = 12 and remainder = 3.
If we divide 12 by 10, we get quotient = 1 and remainder = 2.
Finally, dividing 1 by 10 gives quotient = 0 and remainder = 1.
By repeatedly dividing a number by 10, we can extract all its digits.
So the digits of 1234 are: 4, 3, 2, 1 (in reverse order).
Now, if we add them: 1 + 2 + 3 + 4 = 10. Done!
󼩺󼩻 Step 2: Deciding the Logic in Words
1. Ask the user for a number.
2. Send that number to a function, say sumOfDigits().
3. Inside the function:
o Initialize sum = 0.
o While the number is not zero:
Get the last digit using % 10.
Add this digit to sum.
Remove the last digit by dividing the number by 10.
o Return the sum.
4. Print the result in the main() function.
󼩺󼩻 Step 3: Writing the Program in C
Here’s the actual C code:
#include <stdio.h>
// Function to calculate sum of digits
int sumOfDigits(int num) {
int sum = 0, digit;
Easy2Siksha.com
while(num != 0) {
digit = num % 10; // Get last digit
sum = sum + digit; // Add digit to sum
num = num / 10; // Remove last digit
}
return sum;
}
int main() {
int number, result;
// Ask user for input
printf("Enter a number: ");
scanf("%d", &number);
// Call the function
result = sumOfDigits(number);
// Display the result
printf("The sum of digits of %d is: %d\n", number, result);
return 0;
}
󹶓󹶔󹶕󹶖󹶗󹶘 Explanation of the Program Line by Line
1. #include <stdio.h>
We include this header file to use printf and scanf.
2. int sumOfDigits(int num) { ... }
This is our function that accepts an integer num and returns the sum of its digits.
3. Inside the function:
o while(num != 0) → This loop runs until the number becomes zero.
o digit = num % 10; → Finds the last digit.
o sum = sum + digit; → Adds the digit to our running total.
o num = num / 10; → Removes the last digit.
4. int main() → The starting point of the program.
5. scanf("%d", &number); → Takes input from the user.
6. result = sumOfDigits(number); → Calls the function to calculate the sum.
7. printf("The sum of digits of %d is: %d\n", number, result);
Finally, the result is displayed.
󷈷󷈸󷈹󷈺󷈻󷈼 Example Runs
Input: 1234
Output: The sum of digits of 1234 is: 10
Input: 2468
Output: The sum of digits of 2468 is: 20
Input: 999
Output: The sum of digits of 999 is: 27
Easy2Siksha.com
󼩏󼩐󼩑 Why Use a Function?
You may askwhy not just write everything inside main()?
Well, functions have many benefits:
1. Reusability: Once written, you can use sumOfDigits() again and again without
rewriting the logic.
2. Clarity: The program looks cleaner, because main() only controls the flow, while the
function does the calculation.
3. Maintainability: If tomorrow you want to improve the logic, you only need to update
the function, not the entire program.
󷇮󷇭 Real-Life Analogy
Think of the process like this:
You are the main() function.
Your calculator is the sumOfDigits() function.
You just give the calculator a number, and it does the hard work of breaking it down
and adding digits.
Finally, you display the answer proudly.
This is exactly how teamwork works in programmingone part takes care of input/output,
while another part focuses on calculations.
󽆪󽆫󽆬 Conclusion
So, the question which at first looked a bit technical is actually very simple. It’s just like
playing with numbers: break them apart, add their pieces, and you’re done. By using
functions, we make our program elegant and organized.
Now, whenever your teacher or examiner asks, “How do you write a program to find the
sum of digits of a number in C?” you not only have the code but also the story, logic, and
reasoning to explain it beautifully.
This is the real beauty of programming—it’s not about typing symbols but about solving
problems step by step, just like solving puzzles.
Easy2Siksha.com
6.(a) What is Recursion ? Explain with the help of an example.
(b) What is a string in C ? Explain any five string handling functions available in C.
Ans: Imagine you are climbing a tall staircase. At every step, instead of directly running up
all the stairs, you decide:
“I’ll just take one step now, and then ask myself to repeat the same task again for the
remaining stairs.”
This simple idea of breaking down a big problem into smaller, similar problems is exactly
what Recursion in programming is all about. Let’s unfold this concept slowly, like a story,
and then we’ll move to the second part: strings in C.
(a) What is Recursion?
In computer science, Recursion is a technique where a function calls itself directly or
indirectly to solve a problem. At first, it might look strangelike someone writing their own
name again and againbut in reality, recursion is one of the most powerful problem-solving
methods.
The two important ingredients of recursion are:
1. Base Case (Stopping Point):
Just like climbing stairs, there must be a step where you finally stop. Without it,
you’ll keep going forever and crash into an “infinite loop.”
2. Recursive Case (Self-Call):
This is the part where the function calls itself to solve a smaller version of the same
problem.
A Simple Story Example: Factorial of a Number
Suppose you want to calculate factorial of 5 (written as 5!).
Factorial means:
5!=5×4×3×2×15! = 5 × 4 × 3 × 2 × 15!=5×4×3×2×1
Instead of multiplying everything at once, you can think like this:
“The factorial of 5 is 5 × factorial of 4.”
Similarly, factorial of 4 is 4 × factorial of 3.
This continues until factorial of 1, which is just 1.
So the big task of calculating 5! gets broken down into smaller tasks until it becomes trivial.
Easy2Siksha.com
C Program for Factorial using Recursion
#include <stdio.h>
// Recursive function to calculate factorial
int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: factorial of 0 or 1 is 1
} else {
return n * factorial(n - 1); // Recursive call
}
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("Factorial of %d is: %d\n", number, factorial(number));
return 0;
}
How This Works
If you enter 5:
1. factorial(5) → 5 × factorial(4)
2. factorial(4) → 4 × factorial(3)
3. factorial(3) → 3 × factorial(2)
4. factorial(2) → 2 × factorial(1)
5. factorial(1) → returns 1 (base case)
Now, the values come back step by step like dominos falling backward:
5 × 4 × 3 × 2 × 1 = 120
That’s the magic of recursion—solving big tasks by cutting them into smaller, repeated
steps.
(b) What is a String in C?
Now let’s move to the second part.
Imagine you’re sending a message to your friend. The message is made up of words, and
words are made up of characters like H, e, l, l, o.
In the C programming language, when we want to work with a group of characters, we use
a String.
󷷑󷷒󷷓󷷔 In C, a String is basically a 1-dimensional array of characters that ends with a special
character called the null character ('\0').
Easy2Siksha.com
For example:
char name[] = "Rishabh";
Here, behind the scenes, the computer stores it as:
R i s h a b h \0
That \0 at the end is very important. It tells the computer: “This is where the string ends.”
String Handling Functions in C
Since strings are used everywhere (names, sentences, passwords, etc.), the C language
provides many ready-made functions in the string.h library. Let’s explore five very common
ones with short stories and examples.
1. strlen() Length of a String
Imagine you want to know how long a road is before walking on it. Similarly, before using a
string, we may want to know how many characters it has.
The strlen() function counts the number of characters in a string (but not the \0).
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello World";
printf("Length of string is: %lu\n", strlen(str));
return 0;
}
Output: 11
2. strcpy() Copy One String into Another
Suppose you want to copy your homework to a new notebook.
Similarly, strcpy() copies the content of one string into another.
Example:
#include <stdio.h>
#include <string.h>
int main() {
Easy2Siksha.com
char source[] = "Programming";
char target[20];
strcpy(target, source);
printf("Copied string is: %s\n", target);
return 0;
}
3. strcat() Concatenate (Join) Two Strings
Think of joining two train compartments to make a longer train.
strcat() joins (appends) one string at the end of another.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[30] = "Hello ";
char str2[] = "World";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
Output: Hello World
4. strcmp() Compare Two Strings
Imagine two people are asked to write their names on a form. You want to check if both
wrote the same thing.
strcmp() compares two strings:
If they are the same → returns 0.
If the first is greater → positive value.
If the second is greater → negative value.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Orange";
if (strcmp(str1, str2) == 0)
printf("Strings are equal\n");
else
Easy2Siksha.com
printf("Strings are not equal\n");
return 0;
}
5. strrev() Reverse a String
Think of standing in front of a mirror; you see the reverse of yourself.
Similarly, strrev() reverses the order of characters in a string.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Computer";
printf("Reversed string: %s\n", strrev(str));
return 0;
}
Output: retupmoC
Conclusion
So, let’s tie everything together.
Recursion is like breaking a mountain into smaller rocks and solving the problem
step by step, as we saw with the factorial program.
Strings in C are like sentences we use in daily life, represented as arrays of characters
ending with \0.
With the help of powerful functions like strlen(), strcpy(), strcat(), strcmp(),
and strrev(), we can handle text efficiently in C.
By understanding recursion and strings, we unlock two doors in programming: one that
helps us think in terms of repeated tasks (recursion), and another that helps us deal with
real-world text (strings).
Both are fundamental, both are fascinating, and together they make C programming not just
logicalbut also a bit like storytelling itself.
Easy2Siksha.com
SECTIOND
7. What is User defined data type ? What is use of structure and union in C ? What is
difference between both ?
Ans: 󷊆󷊇 The Story of User-Defined Data Types, Structures, and Unions in C
Imagine you are a chef in a huge restaurant kitchen. Every day, you deal with basic
ingredients like salt, sugar, rice, wheat, and spices. These are like the basic data types in C
int, float, char, double, etc.
But what if one day, your boss tells you:
“We need to serve a special dish that combines rice, vegetables, spices, and sauce together.
You cannot serve them separately, they must be together as one plate.”
Suddenly, you realize that using only basic ingredients is not enough. You need a new
customized dish that combines many ingredients under one name.
This is exactly why user-defined data types exist in C.
󷈷󷈸󷈹󷈺󷈻󷈼 What is a User-Defined Data Type?
In C, user-defined data types are those which programmers create themselves to represent
complex or customized data in a neat and organized way.
Instead of relying only on built-in types like int or float, you can design your own “dish”
(data type) to bundle related values together.
Examples of user-defined data types are:
typedef (to give a new name to an existing data type)
enum (for enumeration of constant values)
struct (to group variables of different types together)
union (to group variables but share the same memory space)
Among these, the most powerful and widely used are structures and unions.
󷩆󷩇󷩈󷩉󷩌󷩊󷩋 Structure in C The Organized Building
Think of a structure like a building with many rooms. Each room has its own space, and you
can store different items in different rooms without disturbing others.
Easy2Siksha.com
In C, a structure allows you to combine variables of different data types under one name.
󷷑󷷒󷷓󷷔 Definition:
A structure is a user-defined data type in C that groups together variables of different data
types under a single name, where each member has its own separate memory space.
󽆪󽆫󽆬 Example of a Structure
Suppose we want to store information about a student:
Name (string/character array)
Age (integer)
Marks (float)
Instead of creating three separate variables for every student, we can group them together
in a structure:
#include <stdio.h>
#include <string.h>
struct Student {
char name[30];
int age;
float marks;
};
int main() {
struct Student s1;
strcpy(s1.name, "Ravi Kumar");
s1.age = 20;
s1.marks = 85.6;
printf("Student Details:\n");
printf("Name: %s\n", s1.name);
printf("Age: %d\n", s1.age);
printf("Marks: %.2f\n", s1.marks);
return 0;
}
󹼧 Here, the structure Student works like a container that holds name, age, and marks
together.
󷘹󷘴󷘵󷘶󷘷󷘸 Uses of Structure
1. To represent complex entities (like student, employee, book, car, etc.).
2. To organize different data types under a single name.
Easy2Siksha.com
3. To create arrays of structures (e.g., list of students).
4. To pass groups of data to functions easily.
5. To implement records, databases, and even linked lists, trees, and other data
structures.
󷘧󷘨 Union in C The Magic Closet
Now imagine another situation: You live in a small apartment with one single closet. You
can keep your clothes, books, or shoes in that closet, but not all at the same time. If you put
books in, you’ll have to take out the clothes.
This is exactly how a union works in C.
󷷑󷷒󷷓󷷔 Definition:
A union is a user-defined data type in C that groups variables of different data types under a
single name, but all members share the same memory space.
󽆪󽆫󽆬 Example of a Union
Suppose we want to store data of an item that can either have:
an integer ID, or
a floating-point price, or
a character code
We can use a union:
#include <stdio.h>
#include <string.h>
union Item {
int id;
float price;
char code;
};
int main() {
union Item item1;
item1.id = 101;
printf("Item ID: %d\n", item1.id);
item1.price = 299.99;
printf("Item Price: %.2f\n", item1.price);
item1.code = 'A';
printf("Item Code: %c\n", item1.code);
Easy2Siksha.com
return 0;
}
󽁔󽁕󽁖 Notice something important:
When we assign price, the previous value of id is lost. When we assign code, the value of
price is lost.
That’s because all members share the same memory space.
󷘹󷘴󷘵󷘶󷘷󷘸 Uses of Union
1. To save memory when only one variable is needed at a time.
2. Useful in embedded systems where memory is limited.
3. Used in device drivers, low-level programming, and situations where data may be of
different types at different times.
4. Helps create structures like variant data types.
󽀼󽀽󽁀󽁁󽀾󽁂󽀿󽁃 Difference Between Structure and Union
Let’s compare them like two brothers – one who owns a big house (Structure) and one who
lives in a single small room (Union).
Feature
Structure
Union
Memory
Allocation
Each member gets its own
memory space.
All members share the same memory
space.
Size
Total size = sum of sizes of all
members.
Total size = size of the largest member.
Access
All members can be used
simultaneously.
Only one member can hold a value at a
time.
Usage
Suitable for storing multiple
related values.
Suitable when storing only one value
at a time to save memory.
Example
Student info (name, age,
marks together).
Item info (id OR price OR code).
󼩏󼩐󼩑 Why Both Are Important?
Structures are like diaries where you can write many details at the same time.
Unions are like chalkboards you can write one thing, erase it, and then write
another.
Both are essential:
Structures give organization.
Easy2Siksha.com
Unions give memory efficiency.
󷊭󷊮󷊯󷊱󷊰󷊲󷊳󷊴󷊵󷊶 Conclusion
C language is like a toolkit. The built-in types (int, float, char) are like simple tools a
hammer, a screwdriver, a wrench. But sometimes, you need a special customized tool to
solve a unique problem. That’s where user-defined data types come in.
Structures let you group different data types together neatly, like compartments in a
cupboard.
Unions let you share the same space for different needs, like a single locker used for
different items.
The key difference lies in memory management: structures allocate separate space,
unions share one space.
So, next time you write a C program, think like a chef or a builder: sometimes you need a big
house with many rooms (Structure), and sometimes you just need a small room that
changes purpose (Union). That’s the beauty of user-defined data types they let you design
your own way of handling data!
8. What is a pointer ? Which are different types of pointers in C ? Give examples.
Ans: Pointers in C: A Story of Addresses and Types
Imagine you are at home, and your friend asks you:
"Hey, where’s the library?"
Now, instead of carrying the whole library to your friend (which is impossible!), you just give
them the address of the library. With that address, your friend can directly go there, open
the door, and read as many books as they want.
This is exactly how pointers work in C programming. Instead of carrying actual data around,
a pointer stores the address of that data. With the help of that address, we can find,
change, or use the data whenever needed.
1. What is a Pointer?
In the simplest form:
󷷑󷷒󷷓󷷔 A pointer is a special variable in C that stores the address of another variable.
Easy2Siksha.com
A normal variable (like int x = 10;) directly stores data (in this case, the number 10).
A pointer variable (like int *p;) stores the address of another variable.
It’s like the difference between:
Writing your name on a paper (normal variable, direct value).
Writing your house address on a paper (pointer, address).
The beauty is: with the address, we can always reach the real value.
Example 1: Basic Pointer
#include <stdio.h>
int main() {
int num = 25; // normal variable
int *ptr; // pointer variable
ptr = &num; // pointer stores address of num
printf("Value of num: %d\n", num); // prints 25
printf("Address of num: %p\n", &num); // prints address
printf("Pointer holds: %p\n", ptr); // same address
printf("Value via pointer: %d\n", *ptr); // prints 25
return 0;
}
Explanation:
&num means “address of num”.
*ptr means “value at the address stored in ptr” (called dereferencing).
So pointers connect the dots between address and value.
2. Why Do We Need Pointers?
You may ask: “Why can’t we just use variables directly?”
Well, pointers give us superpowers in C:
1. They make functions powerful (passing references instead of just values).
2. They allow dynamic memory allocation (memory created at runtime).
3. They help in data structures like linked lists, trees, stacks, etc.
4. They are useful for arrays and strings.
So, pointers are not just another concept; they are the backbone of C’s flexibility.
Easy2Siksha.com
3. Types of Pointers in C
Like people have different roles (doctor, teacher, student), pointers also come in different
types, each serving a specific role. Let’s meet them one by one.
a) Null Pointer
This is a pointer that points to nothing.
It’s like having an empty address book entry—no house to visit.
#include <stdio.h>
int main() {
int *ptr = NULL; // pointer with no valid address
printf("Value of ptr: %p\n", ptr);
return 0;
}
Output will show 0x0 or (nil) depending on compiler.
Null pointers are used for safety, so we don’t accidentally access garbage memory.
b) Void Pointer
Also called a generic pointer, it can hold the address of any data type.
It’s like a “master key” that can fit into different locks.
#include <stdio.h>
int main() {
int num = 50;
float f = 5.5;
void *ptr; // generic pointer
ptr = &num;
printf("Integer value: %d\n", *(int *)ptr);
ptr = &f;
printf("Float value: %.2f\n", *(float *)ptr);
return 0;
}
Here, the void pointer adjusts itself to point to int or float, depending on how we cast it.
c) Wild Pointer
Easy2Siksha.com
A wild pointer is like a lost travelerit points somewhere random because it was never
initialized.
Accessing it is dangerous, like entering a stranger’s house.
#include <stdio.h>
int main() {
int *ptr; // uninitialized pointer (wild)
// *ptr = 10; // dangerous, may crash the program
return 0;
}
d) Dangling Pointer
When a pointer points to memory that has been freed or deleted, it becomes dangling.
It’s like having the address of a demolished house.
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(sizeof(int));
*ptr = 100;
free(ptr); // memory released
// ptr is now dangling
return 0;
}
e) Function Pointer
Pointers can also point to functions. This is like saving someone’s phone number—you can
call them whenever needed.
#include <stdio.h>
void greet() {
printf("Hello, world!\n");
}
int main() {
void (*funcPtr)(); // function pointer
funcPtr = greet;
funcPtr(); // calling function via pointer
return 0;
}
f) Pointer to Pointer
Yes, pointers can also point to other pointers.
It’s like having the address of a person who knows another address.
#include <stdio.h>
int main() {
int num = 42;
int *ptr = &num; // pointer to int
int **pptr = &ptr; // pointer to pointer
Easy2Siksha.com
printf("Value of num: %d\n", **pptr); // prints 42
return 0;
}
g) Constant Pointer and Pointer to Constant
There’s a small twist with constants:
Pointer to constant → the data can’t be changed through the pointer.
Constant pointer → the pointer itself can’t move to another address.
#include <stdio.h>
int main() {
int x = 10, y = 20;
const int *p1 = &x; // pointer to constant
// *p1 = 30; // not allowed
p1 = &y; // allowed
int *const p2 = &x; // constant pointer
*p2 = 30; // allowed
// p2 = &y; // not allowed
return 0;
}
4. The Big Picture
If we look back at all the types:
1. Null Pointer → points nowhere.
2. Void Pointer → can point anywhere (generic).
3. Wild Pointer → uninitialized and dangerous.
4. Dangling Pointer → points to deleted memory.
5. Function Pointer → points to functions.
6. Pointer to Pointer → chain of pointers.
7. Constant Pointers → restrictions on movement or modification.
Each has its role, just like different professions in society.
5. Conclusion: The Beauty of Pointers
Pointers may seem tricky at first, but once you understand them, they become your best
friend in C.
They help you:
Work with memory directly.
Easy2Siksha.com
Create advanced data structures.
Write efficient programs.
So, next time you think about pointers, just imagine an address leading you straight to the
treasure chest of data. Without pointers, C would be like a city without street addresses
confusing and incomplete.
“This paper has been carefully prepared for educational purposes. If you notice any mistakes or
have suggestions, feel free to share your feedback.”